#include <my_header.h>
//  -  如果缓冲区中存在数据，但是数据一直没有增多，那么e
// poll_wait就不会就绪，只有缓冲区的数据增多的时候，才能使epoll_wait就绪。
//   边缘触发的设置,  是在`epoll_ctl`的时候, 
//   给`struct epoll_event *event`参数的`events`设置`EPOLLET` 
/* Usage: ./8_server_poll_边缘触发 */
int main(void){                      
    // 服务端 ip和端口
    char *ip = "192.168.229.128";
    char *port = "8080";

    // 创建socket对象
    int sofd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sofd, -1, "socket");

    // 创建struct sockaddr 类型
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(port));
    server_addr.sin_addr.s_addr = inet_addr(ip);

    // 绑定端口
    int res_bind = bind(sofd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    ERROR_CHECK(res_bind, -1, "bind");

    // 监听
    int res_lis = listen(sofd, 10);
    ERROR_CHECK(res_lis, -1, "listen");

    // 获取连接
    int net_fd = accept(sofd, NULL, NULL);
    ERROR_CHECK(net_fd, -1, "accept");
    // 创建epoll对象    通信
    int epoll_fd = epoll_create(1);
    ERROR_CHECK(epoll_fd, -1, "epoll_create");

    // 放入监听
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = STDIN_FILENO;
    int res_epoctl = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    ERROR_CHECK(res_epoctl, -1, "epoll_ctl");

    event.events = EPOLLIN;
    event.data.fd = net_fd;
    int res_epoctl1 = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, net_fd, &event);
    ERROR_CHECK(res_epoctl1, -1, "epoll_ctl");

    int flag = 0;
    while(1)
    {
        // 开始监听
        struct epoll_event list[10];
        memset(list, 0, sizeof(list));
        int epoll_num = epoll_wait(epoll_fd, list, 10, -1);

        // 循环遍历 处理就绪问题
        for(int i = 0; i<epoll_num; i++)
        {
            int fd = list[i].data.fd;
            
            if(fd == net_fd)
            {
                // 对端发送信息
                char buf[60] = { 0 };
                int ret_recv = recv(net_fd, buf, sizeof(buf), 0);
                if(ret_recv == 0)
                {
                    printf("client closed! \n");
                    flag =1;
                    break;
                }
                printf("client message : %s\n", buf);

            }else if(fd == STDIN_FILENO)
            {
                char buf[60] = { 0 };
                read(STDIN_FILENO, buf, sizeof(buf));
                int ret_send = send(net_fd, buf, sizeof(buf), 0);
                ERROR_CHECK(ret_send, -1, "send");
            }
        }
        if(flag != 0)
        {
            break;
        }
    }

    close(sofd);
    close(net_fd);
    return 0;

}


